package com.pzh.xzh.other.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;

@Configuration
public class MyResourceServerConfig extends ResourceServerConfigurerAdapter {

    private final static String APP_CLIENT_ID="salary";
    @Autowired
    private TokenStore tokenStore;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.authorizeRequests()//校验请求
                .antMatchers("/salary/**")
                .access("#oauth2.hasScope('all')")
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                .resourceId(APP_CLIENT_ID) //客户端id
                //.tokenServices(tokenServices()) //远程校验
                .tokenStore(tokenStore) //使用自己进行jwt校验
                .stateless(false);//无状态模式
        //super.configure(resources);
    }
    @Bean
    public ResourceServerTokenServices tokenServices(){
        RemoteTokenServices remoteTokenServices=new RemoteTokenServices();//远程方式
        remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:8899/oauth/check_token");//设置远程校验端口地址
        remoteTokenServices.setClientId("c1");
        remoteTokenServices.setClientSecret("xzh");
        return remoteTokenServices;
    }
}
